<template>
  <el-dialog
    v-model="visible"
    title="在线客服"
    width="900px"
    :close-on-click-modal="false"
    class="merchant-service-dialog"
    :fullscreen="false"
    :show-close="true"
    :modal-class="'dark:bg-gray-800/90'"
  >
    <template #header>
      <div class="flex items-center">
        <span class="text-lg font-medium">在线客服</span>
      </div>
    </template>
    <div class="flex h-[650px]">
      <!-- 左侧聊天区域 -->
      <div class="flex-1 flex flex-col bg-gray-50 dark:bg-gray-800">
        <!-- 聊天头部 -->
        <div
          class="p-4 bg-white dark:bg-gray-800 border-b dark:border-gray-700 flex items-center justify-between shadow-sm"
        >
          <div
            class="flex items-center gap-3 cursor-pointer group hover:opacity-90 transition-opacity"
            @click="goToShop(merchant.id)"
          >
            <div class="relative">
              <el-avatar
                :size="40"
                :src="merchant.avatar"
                class="shadow-sm group-hover:scale-105 transition-transform"
              />
              <div
                class="absolute -bottom-1 -right-1 w-3 h-3 bg-green-500 rounded-full border-2 border-white dark:border-gray-800"
              ></div>
            </div>
            <div>
              <div
                class="font-medium text-gray-900 dark:text-gray-100 flex items-center gap-1 group-hover:text-primary-500 dark:group-hover:text-primary-400 transition-colors"
              >
                {{ merchant.name }}
                <el-icon
                  class="text-sm opacity-0 group-hover:opacity-100 transition-opacity"
                  ><ArrowRight
                /></el-icon>
              </div>
              <div
                class="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-2"
              >
                <span class="flex items-center gap-1">
                  <div class="w-1.5 h-1.5 bg-green-500 rounded-full"></div>
                  在线
                </span>
                <span>|</span>
                <span>平均响应: 2分钟</span>
              </div>
            </div>
          </div>
          <div class="flex items-center gap-2">
            <el-tooltip content="清空聊天记录" placement="top">
              <el-button
                type="danger"
                :icon="Delete"
                circle
                plain
                size="small"
                @click="clearChat"
              />
            </el-tooltip>
            <el-tooltip content="查看历史消息" placement="top">
              <el-button
                type="primary"
                :icon="More"
                circle
                plain
                size="small"
                @click="viewHistory"
              />
            </el-tooltip>
          </div>
        </div>

        <!-- 聊天消息区域 -->
        <div class="flex-1 overflow-y-auto p-4 space-y-4" ref="chatContainer">
          <!-- 系统消息 -->
          <div v-if="messages.length === 0" class="flex justify-center">
            <div
              class="bg-gray-100 dark:bg-gray-700 rounded-lg px-4 py-2 text-sm text-gray-500 dark:text-gray-400"
            >
              暂无聊天记录
            </div>
          </div>
          <!-- 消息列表 -->
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="[
              'flex',
              message.type === 'merchant' ? 'justify-start' : 'justify-end',
            ]"
          >
            <div
              class="flex items-start gap-2 max-w-[70%] group"
              :class="[
                message.type === 'merchant' ? 'flex-row' : 'flex-row-reverse',
              ]"
            >
              <el-avatar
                :size="36"
                :src="
                  message.type === 'merchant' ? merchant.avatar : userAvatar
                "
                class="flex-shrink-0"
              />
              <div
                class="flex flex-col"
                :class="[
                  message.type === 'merchant' ? 'items-start' : 'items-end',
                ]"
              >
                <div class="text-xs text-gray-500 dark:text-gray-400 mb-1">
                  {{ message.time }}
                </div>
                <div
                  class="relative message-bubble"
                  :class="[
                    message.type === 'merchant'
                      ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100'
                      : 'bg-primary-500 text-white',
                    message.type === 'merchant'
                      ? 'message-received'
                      : 'message-sent',
                  ]"
                >
                  <!-- 文本消息 -->
                  <template v-if="message.contentType === 'text'">
                    <div class="whitespace-pre-wrap break-words">
                      {{ message.content }}
                    </div>
                  </template>
                  <!-- 图片消息 -->
                  <template v-else-if="message.contentType === 'image'">
                    <el-image
                      :src="message.content"
                      :preview-src-list="[message.content]"
                      class="max-w-[300px] rounded cursor-zoom-in"
                      fit="cover"
                    />
                  </template>
                  <!-- 商品卡片 -->
                  <template v-else-if="message.contentType === 'product'">
                    <div
                      class="bg-gray-50 dark:bg-gray-800 rounded p-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-600"
                      @click="goToProduct(message.content.id)"
                    >
                      <div class="flex gap-2">
                        <el-image
                          :src="message.content.coverImage"
                          class="w-16 h-16 rounded"
                        />
                        <div class="flex-1 min-w-0">
                          <div class="text-sm font-medium truncate">
                            {{ message.content.name }}
                          </div>
                          <div class="text-primary-500 text-sm mt-1">
                            ¥{{ message.content.price }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </div>
                <!-- 消息操作 -->
                <div
                  class="message-actions opacity-0 group-hover:opacity-100 transition-opacity mt-1 flex items-center gap-2"
                  :class="[
                    message.type === 'merchant'
                      ? 'justify-start'
                      : 'justify-end',
                  ]"
                >
                  <el-button text size="small" @click="copyMessage(message)"
                    >复制</el-button
                  >
                  <el-button
                    v-if="message.type === 'visitor'"
                    text
                    size="small"
                    type="danger"
                    @click="deleteMessage(index)"
                    >删除</el-button
                  >
                </div>
              </div>
            </div>
          </div>
          <!-- 对方正在输入提示 -->
          <div
            v-if="isTyping"
            class="flex items-center gap-2 text-gray-500 dark:text-gray-400"
          >
            <el-avatar :size="36" :src="merchant.avatar" />
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>

        <!-- 工具栏 -->
        <div
          class="bg-white dark:bg-gray-800 border-t dark:border-gray-700 p-2"
        >
          <div class="flex items-center gap-2">
            <el-tooltip content="表情" placement="top">
              <el-popover placement="top" :width="300" trigger="click">
                <template #reference>
                  <el-button :icon="ChatRound" circle plain />
                </template>
                <div class="grid grid-cols-8 gap-2 p-2">
                  <div
                    v-for="emoji in emojis"
                    :key="emoji"
                    class="w-8 h-8 flex items-center justify-center text-lg cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
                    @click="insertEmoji(emoji)"
                  >
                    {{ emoji }}
                  </div>
                </div>
              </el-popover>
            </el-tooltip>
            <el-tooltip content="发送图片" placement="top">
              <el-upload
                class="upload-demo"
                action="/api/upload"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-success="handleUploadSuccess"
              >
                <el-button :icon="PictureIcon" circle plain />
              </el-upload>
            </el-tooltip>
            <el-tooltip content="截图" placement="top">
              <el-button :icon="Camera" circle plain @click="takeScreenshot" />
            </el-tooltip>
            <el-divider direction="vertical" />
            <el-button size="small" @click="sendQuickReply('查询物流')"
              >查询物流</el-button
            >
            <el-button size="small" @click="sendQuickReply('申请退款')"
              >申请退款</el-button
            >
            <el-button size="small" @click="sendQuickReply('修改地址')"
              >修改地址</el-button
            >
          </div>
        </div>

        <!-- 输入区域 -->
        <div
          class="bg-white dark:bg-gray-800 p-4 border-t dark:border-gray-700"
        >
          <div class="flex gap-2">
            <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="3"
              placeholder="请输入消息..."
              resize="none"
              @keydown.enter.prevent="sendMessage"
              @input="handleInput"
            />
            <el-button
              type="primary"
              class="flex-shrink-0"
              :loading="sendLoading"
              @click="sendMessage"
              :disabled="!inputMessage.trim()"
            >
              发送
              <template #icon>
                <el-icon class="ml-1"><Position /></el-icon>
              </template>
            </el-button>
          </div>
          <div class="mt-2 flex justify-between items-center">
            <div class="text-xs text-gray-400">
              按 Enter 发送消息，Shift + Enter 换行
            </div>
            <div class="text-xs text-gray-400">
              {{ inputMessage.length }}/500
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧信息栏 -->
      <div
        class="w-[280px] border-l dark:border-gray-700 bg-white dark:bg-gray-800 overflow-y-auto"
      >
        <!-- 当前咨询商品 -->
        <div class="p-4 border-b dark:border-gray-700">
          <h4 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-3">
            当前咨询商品
          </h4>
          <div
            class="bg-gray-50 dark:bg-gray-700 rounded-lg p-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-600"
            @click="sendProductLink(product)"
          >
            <div class="flex gap-2">
              <el-image
                :src="product.coverImage"
                class="w-16 h-16 rounded object-cover"
              />
              <div class="flex-1 min-w-0">
                <div
                  class="text-sm text-gray-900 dark:text-gray-100 line-clamp-2"
                >
                  {{ product.title }}
                </div>
                <div class="text-sm text-primary-500 mt-1">
                  ¥{{ product.price }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 常见问题 -->
        <div class="p-4">
          <h4 class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-3">
            常见问题
          </h4>
          <div class="space-y-2">
            <div
              v-for="(faq, index) in commonQuestions"
              :key="index"
              class="p-2 text-sm text-gray-600 dark:text-gray-300 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg transition-colors"
              @click="sendQuickReply(faq)"
            >
              {{ faq }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>

  <!-- 历史消息抽屉 -->
  <el-drawer
    v-model="showHistory"
    title="历史消息"
    direction="rtl"
    size="500px"
  >
    <div class="p-4">
      <el-timeline>
        <el-timeline-item
          v-for="(history, index) in chatHistory"
          :key="index"
          :timestamp="history.date"
          placement="top"
        >
          <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
            <div class="text-sm text-gray-900 dark:text-gray-100 mb-2">
              {{ history.title }}
            </div>
            <div class="text-xs text-gray-500">
              {{ history.messages }} 条消息
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </div>
  </el-drawer>
</template>

<script>
import { ref, onMounted, nextTick, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  ChatRound,
  Picture as PictureIcon,
  Camera,
  Delete,
  Position,
  More,
  ArrowRight,
} from "@element-plus/icons-vue";

export default {
  name: "MerchantService",
  props: {
    product: {
      type: Object,
      required: true,
    },
  },
  setup(props) {
    const router = useRouter();
    const visible = ref(false);
    const inputMessage = ref("");
    const isTyping = ref(false);
    const chatContainer = ref(null);
    const sendLoading = ref(false);
    const showHistory = ref(false);

    // 商家信息
    const merchant = ref({
      id: 1,
      name: "贵港优选店铺",
      avatar: "/merchant-avatar.jpg",
      businessHours: "09:00-21:00",
    });

    // 用户头像
    const userAvatar = ref("/user-avatar.jpg");

    // 表情列表
    const emojis = [
      "😊",
      "😂",
      "🤣",
      "😍",
      "😒",
      "😘",
      "🥰",
      "😅",
      "😁",
      "👍",
      "👎",
      "❤️",
      "💔",
      "🎉",
      "🎂",
      "🌹",
    ];

    // 常见问题
    const commonQuestions = [
      "商品是否有现货？",
      "可以发顺丰吗？",
      "有优惠活动吗？",
      "支持七天无理由退换吗？",
      "可以开发票吗？",
      "有其他颜色吗？",
    ];

    // 历史消息
    const chatHistory = [
      { date: "2024-03-20", title: "咨询商品详情", messages: 12 },
      { date: "2024-03-19", title: "售后服务咨询", messages: 8 },
      { date: "2024-03-18", title: "物流查询", messages: 5 },
    ];

    // 聊天消息
    const messages = ref([
      {
        type: "merchant",
        contentType: "text",
        content: "您好！很高兴为您服务，请问有什么可以帮您的吗？",
        time: new Date().toLocaleTimeString(),
      },
      {
        type: "merchant",
        contentType: "product",
        content: props.product,
        time: new Date().toLocaleTimeString(),
      },
    ]);

    // 复制消息
    const copyMessage = (message) => {
      if (message.contentType === "text") {
        navigator.clipboard.writeText(message.content);
        ElMessage.success("消息已复制到剪贴板");
      }
    };

    // 删除消息
    const deleteMessage = (index) => {
      messages.value.splice(index, 1);
      ElMessage.success("消息已删除");
    };

    // 清空聊天
    const clearChat = () => {
      ElMessageBox.confirm("确定要清空所有聊天记录吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        messages.value = [];
        ElMessage.success("聊天记录已清空");
      });
    };

    // 查看历史消息
    const viewHistory = () => {
      showHistory.value = true;
    };

    // 滚动到底部
    const scrollToBottom = async () => {
      await nextTick();
      if (chatContainer.value) {
        chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
      }
    };

    // 发送消息
    const sendMessage = async () => {
      if (!inputMessage.value.trim()) return;

      sendLoading.value = true;
      try {
        const message = {
          type: "visitor",
          contentType: "text",
          content: inputMessage.value,
          time: new Date().toLocaleTimeString(),
        };
        messages.value.push(message);
        inputMessage.value = "";

        // 滚动到底部
        await scrollToBottom();

        // 显示对方正在输入
        isTyping.value = true;

        // 模拟客服回复
        setTimeout(() => {
          isTyping.value = false;
          messages.value.push({
            type: "merchant",
            contentType: "text",
            content: "好的，我来为您介绍一下这款商品...",
            time: new Date().toLocaleTimeString(),
          });
          scrollToBottom();
        }, 1500);
      } finally {
        sendLoading.value = false;
      }
    };

    // 发送商品链接
    const sendProductLink = (product) => {
      messages.value.push({
        type: "visitor",
        contentType: "product",
        content: product,
        time: new Date().toLocaleTimeString(),
      });
      scrollToBottom();

      // 模拟客服回复
      setTimeout(() => {
        messages.value.push({
          type: "merchant",
          contentType: "text",
          content: `您好，${product.title} 目前有货，请问您想了解哪些具体信息呢？`,
          time: new Date().toLocaleTimeString(),
        });
        scrollToBottom();
      }, 1000);
    };

    // 插入表情
    const insertEmoji = (emoji) => {
      inputMessage.value += emoji;
    };

    // 上传图片
    const beforeUpload = (file) => {
      const isImage = file.type.startsWith("image/");
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        ElMessage.error("只能上传图片文件！");
        return false;
      }
      if (!isLt2M) {
        ElMessage.error("图片大小不能超过 2MB！");
        return false;
      }
      return true;
    };

    const handleUploadSuccess = (response) => {
      messages.value.push({
        type: "visitor",
        contentType: "image",
        content: response.url,
        time: new Date().toLocaleTimeString(),
      });
      scrollToBottom();
    };

    // 截图
    const takeScreenshot = () => {
      ElMessage.info("截图功能开发中...");
    };

    // 发送快速回复
    const sendQuickReply = (content) => {
      inputMessage.value = content;
      sendMessage();
    };

    // 输入提示
    const handleInput = () => {
      if (inputMessage.value.length > 500) {
        inputMessage.value = inputMessage.value.slice(0, 500);
      }
    };

    // 跳转到商品详情
    const goToProduct = (productId) => {
      router.push(`/shop/product/${productId}`);
    };

    // 打开客服窗口
    const open = () => {
      visible.value = true;
    };

    // 跳转到店铺页面
    const goToShop = (shopId) => {
      router.push(`/shop/store/${shopId}`);
    };

    // 监听消息变化，自动滚动到底部
    watch(messages, () => {
      scrollToBottom();
    });

    onMounted(() => {
      scrollToBottom();
    });

    return {
      visible,
      merchant,
      userAvatar,
      messages,
      inputMessage,
      isTyping,
      chatContainer,
      sendLoading,
      showHistory,
      emojis,
      commonQuestions,
      chatHistory,
      sendMessage,
      sendQuickReply,
      goToProduct,
      open,
      copyMessage,
      deleteMessage,
      clearChat,
      viewHistory,
      insertEmoji,
      beforeUpload,
      handleUploadSuccess,
      takeScreenshot,
      handleInput,
      sendProductLink,
      ChatRound,
      PictureIcon,
      Camera,
      Delete,
      Position,
      More,
      ArrowRight,
      goToShop,
    };
  },
};
</script>

<style lang="scss" scoped>
.merchant-service-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
    @apply dark:bg-gray-800 dark:border dark:border-gray-700;

    .el-dialog__header {
      @apply bg-white dark:bg-gray-800 border-b dark:border-gray-700 mb-0 px-6 py-4;
    }

    .el-dialog__body {
      padding: 0;
    }

    .el-dialog__headerbtn {
      @apply top-4 right-4;
      .el-dialog__close {
        @apply dark:text-gray-400 dark:hover:text-gray-200;
      }
    }
  }
}

.message-bubble {
  @apply rounded-lg p-3 shadow-sm;
  max-width: 100%;
  position: relative;

  &.message-received {
    border-radius: 0 12px 12px 12px;
    &::before {
      content: "";
      position: absolute;
      left: -6px;
      top: 0;
      border-style: solid;
      border-width: 0 8px 8px 0;
      border-color: transparent #fff transparent transparent;
      @apply dark:border-r-gray-700;
    }
  }

  &.message-sent {
    border-radius: 12px 0 12px 12px;
    &::before {
      content: "";
      position: absolute;
      right: -6px;
      top: 0;
      border-style: solid;
      border-width: 8px 8px 0 0;
      border-color: var(--el-color-primary) transparent transparent transparent;
    }
  }
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 2px;
  padding: 8px 12px;
  background: white;
  border-radius: 20px;
  @apply dark:bg-gray-700;

  span {
    width: 6px;
    height: 6px;
    background: #90959a;
    border-radius: 50%;
    animation: typing 1s infinite;
    @apply dark:bg-gray-400;

    &:nth-child(1) {
      animation-delay: 0s;
    }
    &:nth-child(2) {
      animation-delay: 0.2s;
    }
    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes typing {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-4px);
  }
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
